package com.cw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.config.JwtConfig;
import com.cw.entity.*;
import com.cw.entity.dto.ReportResponseTemplate;
import com.cw.entity.dto.OrdersDto;
import com.cw.handler.CustomException;
import com.cw.mapper.OrdersMapper;
import com.cw.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService  {
    @Autowired
    private ShoppingCartService shoppingCartService;//1.取出菜品	2清空

    @Autowired
    private UserService userService;//获取下单人信息name

    @Autowired
    private AddressBookService addressBookService;//查地址信息

    @Autowired
    private OrderDetailService orderDetailService;//订单详细信息


    /**
     * 用户下单
     * @param orders

    2个save
    order  save  ;orderDetail    saveBatch
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(Orders orders, HttpServletRequest request) {
        //获得当前用户id
        Long userId = JwtConfig.getCurrentId(request);

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
        log.info("{}",shoppingCarts);
        if(shoppingCarts == null || shoppingCarts.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }

        //查询用户数据
        User user = userService.getById(userId);

        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }
        //订单号
        long orderId = IdWorker.getId();

        /*原子操作：确保线程安全。。订单总金额*/
        AtomicReference<BigDecimal> sum= new AtomicReference<>(new BigDecimal(3));
        //组装订单明细信息
        AtomicReference<Integer> number= new AtomicReference<>(0);
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            number.updateAndGet(v -> v + item.getNumber());
            sum.updateAndGet(v -> v.add( item.getAmount().multiply(BigDecimal.valueOf(item.getNumber())).setScale(2, RoundingMode.HALF_UP)));
            return orderDetail;
        }).collect(Collectors.toList());
        //组装订单数据
        orders.setId(orderId);
        orders.setCreateTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        //总金额+运费
        orders.setAmount(sum.get());
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(number));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getUniName() == null ? "" : addressBook.getUniName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.remove(wrapper);
    }

    @Override
    public IPage<OrdersDto> pageList(Page<Orders> ordersPage, LambdaQueryWrapper<Orders> wrapper) {
        Page<Orders> selectPage = this.baseMapper.selectPage(ordersPage, wrapper);
        List<Orders> records = selectPage.getRecords();
        List<OrdersDto> ordersDtos = new ArrayList<>();
        for (Orders o:records
             ) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(o,ordersDto);
            List list = this.orderDetailService.list(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, o.getId()));
            ordersDto.setOrderDetails(list);
            ordersDtos.add(ordersDto);
        }
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(selectPage,ordersDtoPage);
        ordersDtoPage.setRecords(ordersDtos);
        return ordersDtoPage;
    }

    @Override
    public List<ReportResponseTemplate> monthlyReport() {
        return this.baseMapper.monthlyReport();
    }

}
